package com.memorywords.service.impl;

import com.memorywords.mapper.UserMapper;
import com.memorywords.pojo.User;
import com.memorywords.service.UserService;
import com.memorywords.utils.Md5Util;
import com.memorywords.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender mailSender;

    //注册
    @Override
    public void register(String username, String password, String email) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        userMapper.add(username, md5String, email);
    }

    //根据用户名查询用户
    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public void exitPwd(String newPassword) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("userId");
        System.out.println(id);
        userMapper.exitPwd(Md5Util.getMD5String(newPassword), id);
    }

    @Override
    public void getEmail(String email, String code) {
//        MimeMessage mimeMessage = mailSender.createMimeMessage();
//        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
//        try {
//            mimeMessageHelper.setFrom("19606363088@163.com");
//            mimeMessageHelper.setTo(email);
//            mimeMessageHelper.setSubject("验证码");
//        } catch (MessagingException e) {
//            throw new RuntimeException(e);
//        }
//        Context context = new Context();
//        context.setVariable("email", email);
//        context.setVariable("code", code);
//        mailSender.send(mimeMessage);

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("19606363088@163.com");
        mailMessage.setTo(email);
        mailMessage.setSubject("验证码");
        mailMessage.setText("您的验证码，5分钟内有效。");
        mailMessage.setText(code);
        mailSender.send(mailMessage);
    }

    @Override
    public void updatePgs(int progress, int id) {
        userMapper.updatePgs(progress, id);
    }
}
